package busmap.main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class Map extends MapActivity  {
  	// Configures
   	private static final int FROM_POINT = 1;
   	private static final int TO_POINT = 2;
	private static final int ZOOM = 15;
	private static final GeoPoint point = new GeoPoint( (int) (10.780655 *1E6) ,(int) (106.6691140 * 1E6));
	
	//Variable
	public MapView mapView;
	public GeoPoint From_GeoPoint = null;
	public GeoPoint To_GeoPoint = null;
	private MyOverLay overlay;
	private TableLayout search_box;
	private AutoCompleteTextView input_from_point;
	private AutoCompleteTextView input_to_point;
	private MyItemOverlay itemizedoverlay;   
   	private MyLocationOverlay myLocationOverlay; 
	private int from_index = 0;
	private int to_index = 0;
	private OverlayItem From_Overlay = null;
	private OverlayItem To_Overlay = null;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);	 
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.map_search:
	            //search on the Map
	        	map_search();
	            return true;
	        case R.id.map_refresh:
	        	map_refresh();
	        	//refresh map
	        	return true;
	        case R.id.map_mylocation:
	        	//update my location
	        	map_mylocation();
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	private void map_refresh(){
		mapView.getController().animateTo(point);
		mapView.getController().setZoom(ZOOM);	
		mapView.getOverlays().clear();
		mapView.getOverlays().add(overlay);
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
		search_box.setVisibility(View.INVISIBLE);
		input_from_point.setText("");
		input_to_point.setText("");
		From_GeoPoint = null;
		To_GeoPoint = null;
		search_box.invalidate();
		mapView.invalidate();
	}
	
	private void map_search(){		
		search_box.setVisibility(View.VISIBLE);
	}
	private void map_mylocation(){
		myLocationOverlay.enableCompass();
		myLocationOverlay.enableMyLocation();
		myLocationOverlay.runOnFirstFix(new Runnable() { public void run() {
		    mapView.getController().animateTo(myLocationOverlay.getMyLocation()); 
		}});
		mapView.getOverlays().add(myLocationOverlay);
	}
	
	private void search(){		
		String status = "";
		if(From_GeoPoint != null && To_GeoPoint != null){
			
		}
		else if(From_GeoPoint == null && To_GeoPoint == null){
			status = "Bạn chưa chọn điểm khởi hành và điểm kết thúc";
			Toast toast = Toast.makeText(this,status , status.length());
			toast.show();
		}
		else if(From_GeoPoint == null){
			status = "Bạn chưa chọn điểm khởi hành";
			Toast toast = Toast.makeText(this,status , status.length());
			toast.show();
		}
		else{
			status = "Bạn chưa chọn điểm kết thúc";
			Toast toast = Toast.makeText(this,status , status.length());
			toast.show();
		}		
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		mapView = (MapView) findViewById(R.id.googlemap);	
		search_box = (TableLayout) findViewById(R.id.seacrh_box);
		input_from_point = (AutoCompleteTextView) findViewById(R.id.input_from_point);
		input_to_point   = (AutoCompleteTextView) findViewById(R.id.input_to_point);
		String[] places = getResources().getStringArray(R.array.place_array);
		// Create the adapter and set it to the AutoCompleteTextView 
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, places);
		input_from_point.setAdapter(adapter);
		input_to_point.setAdapter(adapter);
		search_box.setVisibility(View.INVISIBLE);
		mapView.setBuiltInZoomControls(true);
		mapView.setEnabled(true);
		mapView.getController().animateTo(point);
		mapView.getController().setZoom(ZOOM);	   
		mapView.getOverlays().clear();	   
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		overlay = new MyOverLay();
		mapView.getOverlays().add(overlay);
		mapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.disableCompass();
		myLocationOverlay.disableMyLocation();
		itemizedoverlay = new MyItemOverlay(this, this.getResources().getDrawable(R.drawable.from_marker));
		mapView.invalidate();
		final Button button = (Button) findViewById(R.id.button_search_map);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
             search();
            }
        });
	}
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	private void createMarker(GeoPoint p, int marker, int point) {
		if(p == null)
		p = mapView.getMapCenter();
		itemizedoverlay.clear();
		//overlayitem.setMarker(this.getResources().getDrawable(marker));
		switch(point){
			case FROM_POINT:	
				From_Overlay = new OverlayItem(p,"", "");
				break;
			case TO_POINT:
				To_Overlay  = new OverlayItem(p,"", "");
				break;
		}
		if(From_GeoPoint != null) itemizedoverlay.addOverlay(From_Overlay);
		if(To_Overlay != null) itemizedoverlay.addOverlay(To_Overlay);
		if (itemizedoverlay.size() > 0) {
			mapView.getOverlays().add(itemizedoverlay);
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
	}
	@Override
	protected void onPause() {
		super.onResume();
	}
	public class MyItemOverlay extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> overlays = new ArrayList<OverlayItem>();
		private Context context;
		public MyItemOverlay(Context context, Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
			this.context = context;
		}
		public void clear(){
			this.overlays.clear();
		}
		public void setMaker(int drawable){
			boundCenterBottom(context.getResources().getDrawable(drawable));
		}
		@Override
		protected OverlayItem createItem(int i) {
			return overlays.get(i);
		}
		@Override
		public int size() {
			return overlays.size();
		}		
		public void addOverlay(OverlayItem overlay) {
			overlays.add(overlay);
			populate();
		}	
		public void removeOverlay(OverlayItem overlay){
			overlays.remove(overlay);
			populate();
		}
		public void removeOverlay(int index){
			overlays.remove(index);
			populate();
		}
	}
	public class MyOverLay extends Overlay{
		private GeoPoint gp1;
		private GeoPoint gp2;
		private int mRadius=6;
		private int mode=0;
		private int defaultColor =999;
		private Context context;
		private String add = "";
		//Resources res ;
		public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor){
					this.gp1 = gp1;
					this.gp2 = gp2;
					this.mode = mode;
					this.defaultColor = defaultColor;
			}
		public MyOverLay(GeoPoint gp1,GeoPoint gp2,int mode){
			this.gp1 = gp1;
			this.gp2 = gp2;
			this.mode = mode;
		}
		
		public MyOverLay(Context context, GeoPoint point){
			this.gp1 = point;
			this.mode = 1;
			this.context = context;
			//res = context.getResources();
		}
		public MyOverLay() {
			this.mode =0;
			// TODO Auto-generated constructor stub
		}
		@Override
		public boolean onTap(GeoPoint p, final MapView mapView) {
			// TODO Auto-generated method stub
	      	final CharSequence[] items = {"Từ đây", "Đến đây","Trở về"};
	    	final GeoPoint Selected = p;
	    	Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	         try {
	                    List<Address> addresses = geoCoder.getFromLocation(
	                        p.getLatitudeE6()  / 1E6, 
	                        p.getLongitudeE6() / 1E6, 1);	 
	                    add = "";
	                    if (addresses.size() > 0) 
	                    {
	                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
	                           add += addresses.get(0).getAddressLine(i) + "\n";
	                    }	 
	                }
	        catch (IOException e) {                
	             e.printStackTrace();
	        }   	    	
	    	AlertDialog.Builder builder = new AlertDialog.Builder(Map.this);
	    	builder.setTitle(add + "Lat: " + p.getLatitudeE6() + " Lon: " + p.getLongitudeE6());
	    	builder.setItems(items, new DialogInterface.OnClickListener() {
	    	    public void onClick(DialogInterface dialog, int item) {
	    	    	switch(item){
	    	    		case 0:
	    	    			From_GeoPoint = Selected;
	    	    			if(!search_box.isShown())
	    	    				search_box.setVisibility(View.VISIBLE);
	    	    			//if(!add.isEmpty())
	    	    			//	input_from_point.setText(add);
	    	    			if(!Selected.toString().isEmpty())
	    	    				input_from_point.setText(Selected.toString());
	    	    			else
	    	    				input_from_point.setText(R.string.miss_place);
	    	    			createMarker(Selected, R.drawable.from_marker,FROM_POINT);
	    	    			break;
	    	    		case 1:
	    	    			To_GeoPoint = Selected;
	    	    			if(!search_box.isShown())
	    	    				search_box.setVisibility(View.VISIBLE);
	    	    			//if(!add.isEmpty())
	    	    			//	input_to_point.setText(add);
	    	    			if(!Selected.toString().isEmpty())
	    	    				input_to_point.setText(Selected.toString());
	    	    			else
	    	    				input_to_point.setText(R.string.miss_place);
	    	    			createMarker(Selected, R.drawable.to_maker,TO_POINT);
	    	    			break;
	    	    		case 2:	    	    			
	    	    			break;
	    	    	}
	    	    }
	    	});
	    	AlertDialog alert = builder.create();    
	    	alert.show();
	    	return super.onTap(p, mapView);
		}
		
		
		@Override
	    public boolean onTouchEvent(MotionEvent event, MapView mapview){
	        search_box.setVisibility(View.INVISIBLE);
	        search_box.invalidate();
	        return false;
	    }
	  
		/*
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when){
			Projection projection = mapView.getProjection();
			if (shadow == false && mode != 0){
				Paint paint = new Paint();
				paint.setAntiAlias(true);
				Point point = new Point();
				projection.toPixels(gp1, point);
				if(mode==1)
				{
					Point screenPoint = new Point();
				    mapView.getProjection().toPixels(gp1, screenPoint);
					Bitmap markerImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
					paint.setStrokeWidth(1);
				    paint.setARGB(150, 000, 000, 000);
				    paint.setStyle(Paint.Style.STROKE);
				    // Draw it, centered around the given coordinates
				    canvas.drawBitmap(markerImage,
				        screenPoint.x - markerImage.getWidth() / 2,
				        screenPoint.y - markerImage.getHeight() / 2, null);
				    canvas.drawText("Hello" , screenPoint.x- markerImage.getWidth() / 2,  screenPoint.y - markerImage.getHeight() / 2 , paint);
				}
				else if(mode==2){
					if(defaultColor==999)
						paint.setColor(Color.GREEN);
					else
						paint.setColor(defaultColor);
						Point point2 = new Point();
						projection.toPixels(gp2, point2);
						paint.setStrokeWidth(5);
						paint.setAlpha(120);
						canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
				}
				else if(mode==3){
					if(defaultColor==999)
						paint.setColor(Color.RED);
					else
						paint.setColor(defaultColor);
						Point point2 = new Point();
						projection.toPixels(gp2, point2);
						paint.setStrokeWidth(5);
						paint.setAlpha(120);
						canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
						RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
						point2.x + mRadius,point2.y + mRadius);
						 end point 
						paint.setAlpha(255);
						canvas.drawOval(oval, paint);
				}
			}
		return super.draw(canvas, mapView, shadow, when);
		}
		*/
	}
}
 



